//
//  FollowViewController.m
//  XPhoto
//
//  Created by baboy on 2019/8/9.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "FollowViewController.h"
#import "UserFollow.h"
#import "BKIndicator.h"
#import "UserFollowCell.h"
#import "BKIndicator.h"
#import "UserProfileViewController.h"
#import <BKKit/UIImage+x.h>

@interface FollowingTableView()
- (void)follow:(UserFollow *)userFollow;
- (void)unfollow:(UserFollow *)userFollow;
@end

@interface FollowViewController ()<BKScrollViewDragRefreshDelegate>

@end

@implementation FollowViewController
- (void)dealloc{
}
- (id)init{
    if (self = [super initWithNibName:NSStringFromClass([self class]) bundle:nil]){
    }
    return self;
}
- (void)loadView{
    [super loadView];
//    [self.segmentedControl setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor systemBlueColor]} forState:UIControlStateSelected];
//    [self.segmentedControl setBackgroundImage:[UIImage imageWithColor:[UIColor grayColor] size:CGSizeMake(100, 100)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    self.segmentedControl.tintColor = [UIColor redColor];
//    self.segmentedControl.layer.borderColor = [UIColor blueColor].CGColor;
//    self.segmentedControl.layer.cornerRadius = 20;
//    self.segmentedControl.layer.borderWidth = 2;
    self.fanTableView.tableFooterView = [UIView new];
    self.followTableView.tableFooterView = [UIView new];
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:@[NSLocalizedString(@"following", @"按钮"),NSLocalizedString(@"fans", @"按钮")]];
    [_segmentedControl addTarget:self action:@selector(selectedIndexChanged:) forControlEvents:UIControlEventValueChanged];
    
    
}
- (void)setSelectedIndex:(NSInteger)selectedIndex{
    _selectedIndex = selectedIndex;
    CGPoint contentOffset = CGPointZero;
    contentOffset.x = selectedIndex * self.scrollView.bounds.size.width;
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width*2, 0);
    [self.scrollView setContentOffset:contentOffset animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self.segmentedControl removeFromSuperview];
    

    self.fanTableView.delegate = self.fanTableView;
    self.fanTableView.dataSource = self.fanTableView;
    self.fanTableView.uid = self.uid;
    [self.fanTableView searchWithOffset:0];
    
    self.followTableView.delegate = self.followTableView;
    self.followTableView.dataSource = self.followTableView;
    self.followTableView.uid = self.uid;
    
    [self.followTableView searchWithOffset:0];
    
    self.segmentedControl.selectedSegmentIndex = self.selectedIndex;
}
- (IBAction)selectedIndexChanged:(UISegmentedControl *)segmentedControl{
    self.selectedIndex = segmentedControl.selectedSegmentIndex;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * self.selectedIndex, 0);
    self.navigationItem.titleView = self.segmentedControl;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


@implementation FollowingTableView
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_USER_FOLLOWED object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_USER_UNFOLLOWED object:nil];
}
- (void)awakeFromNib{
    [super awakeFromNib];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(follow:) name:NOTIFICATION_USER_FOLLOWED object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(unfollow:) name:NOTIFICATION_USER_UNFOLLOWED object:nil];
}
- (void)searchWithOffset:(NSInteger)offset{
    UserFollowSearchArgs *args = [UserFollowSearchArgs new];
    args.uid = self.uid;
    [UserFollow searchFollows:args
                     callback:^(id task, NSArray  *arr, NSError * error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (arr && [arr count] > 0) {
            self.items = [NSMutableArray arrayWithArray:arr];
            [self removeEmptyIndicator];
            [self reloadData];
        }
        if ( self.items.count == 0 ) {
            [self showEmptyMsg:NSLocalizedString(@"no_request_data", @"提示")
                               icon:nil
                         withTarget:nil
                         withAction:nil];
        }
        [self stopRefreshing];
    }];
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.items.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UserFollowCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UserFollowCell class])];
    if (!cell) {
        cell = loadViewFromNib([UserFollowCell class], self);
        [cell.followButton addTarget:self action:@selector(followOrCancel:) forControlEvents:UIControlEventTouchUpInside];
    }
    User *user = [self.items objectAtIndex:indexPath.row];
    cell.user = user;
    
    UIButton *accessoryButton = (UIButton *)cell.accessoryView;
    [self updateButtonTitle:accessoryButton withUser:user];
    [accessoryButton sizeToFit];
    accessoryButton.layer.cornerRadius = accessoryButton.bounds.size.height/2;
    accessoryButton.tag = indexPath.row;
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    User *user = [self.items objectAtIndex:indexPath.row];
    
    UserProfileViewController *vc = [[UserProfileViewController alloc] init];
    vc.user = user;
    [[self.controller navigationController] pushViewController:vc animated:YES];
    
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(nonnull NSIndexPath *)indexPath{
    
}
- (void)updateButtonTitle:(UIButton *)btn withUser:(User *)user{
    if (user.following) {
        [btn setTitle:NSLocalizedString(@"following", @"标签") forState:UIControlStateNormal];
    }else{
        [btn setTitle:NSLocalizedString(@"follow", @"标签") forState:UIControlStateNormal];
    }
}
- (void)unfollow:(NSInteger)uid withCallback:(nullable void (^)(  NSError * error))callback{

    [BKIndicator showMessage:NSLocalizedString(@"submitting", @"提示")];
    [UserFollow removeFollow:uid callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submit_success", @"提示") completion:nil];
        if (callback) {
            callback(error);
        }
    }];
}
- (void)follow:(NSInteger)uid withCallback:(nullable void (^)(  NSError * error))callback{
    [BKIndicator showMessage:NSLocalizedString(@"submitting", @"提示")];
    [UserFollow addFollow:uid callback:^(id  _Nonnull task, id  _Nullable json, NSError * _Nullable error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
            return;
        }
        [BKIndicator showMessageAndFadeOut:NSLocalizedString(@"submit_success", @"提示") completion:nil];
        if (callback) {
            callback(error);
        }
    }];
}
- (void)followOrCancel:(UIButton *)btn{
    User *user = [self.items objectAtIndex:btn.tag];
    if (user.following) {
        [self unfollow:user.uid withCallback:^(NSError *error) {
            if (!error) {
                user.following = NO;
                [self reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }else{
        [self follow:user.uid withCallback:^(NSError *error) {
            if (!error) {
                user.following = YES;
                [self reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:btn.tag inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
            }
        }];
    }
}

- (void)follow:(NSNotification *)noti{
    UserFollow *userFollow = noti.userInfo[@"data"];
}
- (void)unfollow:(NSNotification *)noti{
    UserFollow *userFollow = noti.userInfo[@"data"];
}
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [scrollView scrollViewDidScroll];
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [scrollView scrollViewDidEndDragging];
}

#pragma mark - BKScrollViewDragRefreshDelegate
- (void)scrollViewWillBeginLoadingMore:(id)scrollView{
    [self searchWithOffset:self.items.count];
}
@end

@implementation FanTableView

- (void)searchWithOffset:(NSInteger)offset{
    UserFollowSearchArgs *args = [UserFollowSearchArgs new];
    args.uid = self.uid;
    [UserFollow searchFans:args
                  callback:^(id task, NSArray  *arr, NSError * error) {
        if (error) {
            [BKIndicator showMessageAndFadeOut:error.localizedDescription completion:nil];
        }
        if (arr && [arr count] > 0) {
            self.items = [NSMutableArray arrayWithArray:arr];
            [self removeEmptyIndicator];
            [self reloadData];
        }
        if ( self.items.count == 0 ) {
            [self showEmptyMsg:NSLocalizedString(@"no_request_data", @"提示")
                          icon:nil
                    withTarget:nil
                    withAction:nil];
        }
        [self stopRefreshing];
    }];
}
- (void)follow:(NSNotification *)noti{
    
}
- (void)unfollow:(NSNotification *)noti{
    
}
@end
